package com.common.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/*  依赖包
	<dependency>
		<groupId>org.apache.httpcomponents</groupId>
		<artifactId>httpclient</artifactId>
		<version>4.3.4</version>
	</dependency>
 */

public class HttpUtil {

    public static String getStringResult(String url){
        final CloseableHttpClient client = HttpClients.createDefault();
        try{
            HttpGet goodsGet = new HttpGet(url);
            HttpResponse httpResponseCoupon = client.execute(goodsGet);
            String result = EntityUtils.toString(httpResponseCoupon.getEntity());
            return result;
        }catch(Exception e){
            return "{'error':请求出错}";
        }finally {
            try {
                client.close();
            } catch (IOException e) {
                return "{'error':关闭client错误}";
            }
        }
    }

    public static JSONObject getJsonResult(String url){
        JSONObject json = JSONObject.parseObject(getStringResult(url));
        return json;
    }

//    public static void setGetHeader(HttpGet httpGet){
//        httpGet.setHeader("Accept","application/json, text/javascript, */*; q=0.01");
//        httpGet.setHeader("X-Requested-With","XMLHttpRequest");
//        httpGet.setHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36");
//        httpGet.setHeader("Accept-Encoding","gzip, deflate, sdch");
//        httpGet.setHeader("Accept-Language","zh-CN,zh;q=0.8");
//        httpGet.setHeader("Cookie","");
//        httpGet.setHeader("Connection","keep-alive");
//        httpGet.setHeader("Host","pub.alimama.com");
//    }

    public static void main(String[] args) {
        String url = "http://pub.alimama.com/items/search.json?toPage=1&perPageSize=10&yxjh=-1&queryType=0&dpyhq=1&shopTag=dpyhq";
        System.out.println(getStringResult(url));

    }
}
